package com.ylr.job.biz.client;


import com.ylr.grpc.ExecutorBiz.ExecutorBizProto;
import com.ylr.job.biz.ExecutorBiz;
import com.ylr.job.biz.model.*;
import com.ylr.job.util.XxlJobRemotingUtil;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * admin api test
 *
 * @author xuxueli 2017-07-28 22:14:52
 */
public class ExecutorBizClient implements ExecutorBiz {




    public ExecutorBizClient() {
    }
    public ExecutorBizClient(String addressUrl, String accessToken) {
        try {
            URL url = new URL(addressUrl);
            this.addressUrl = url.getHost()+":" +url.getPort();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


        this.accessToken = accessToken;
//        // valid
//        if (!this.addressUrl.endsWith("/")) {
//            this.addressUrl = this.addressUrl + "/";
//        }
        this.channel = ManagedChannelBuilder.forTarget(this.addressUrl).usePlaintext().build();

    }

    private String addressUrl ;
    private String accessToken;
    private int timeout = 3;
    private ManagedChannel channel;


    @Override
    public ReturnT<String> beat() throws InterruptedException {

        // 创建到服务器的通信通道，通道是线程安全的和可重用的。
        // 通常在应用程序开始时创建通道，并重用直到应用程序关闭。
        try {
            ExecutorBizProtoClient client = new ExecutorBizProtoClient(channel);
            String beat = client.beat();
            System.out.println(beat);
        } finally {
            // ManagedChannel使用像线程和TCP连接这样的资源。
            // 为了防止泄漏这些资源，通道应该在不再使用时关闭。
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
        return new ReturnT<String>(beat().toString());
    }

    @Override
    public ReturnT<String> idleBeat(IdleBeatParam idleBeatParam){
        return XxlJobRemotingUtil.postBody(addressUrl+"idleBeat", accessToken, timeout, idleBeatParam, String.class);
    }

    @Override
    public ReturnT<String> run(TriggerParam triggerParam) throws InterruptedException {
        // 创建到服务器的通信通道，通道是线程安全的和可重用的。
        // 通常在应用程序开始时创建通道，并重用直到应用程序关闭。
        ReturnT<String> res;
        try {
            ExecutorBizProtoClient client = new ExecutorBizProtoClient(channel);
             res = client.run(triggerParam);
            System.out.println(res);
        } finally {
            // ManagedChannel使用像线程和TCP连接这样的资源。
            // 为了防止泄漏这些资源，通道应该在不再使用时关闭。
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
        return res;

    }

    @Override
    public ReturnT<String> kill(KillParam killParam) {
        return XxlJobRemotingUtil.postBody(addressUrl + "kill", accessToken, timeout, killParam, String.class);
    }

    @Override
    public ReturnT<LogResult> log(LogParam logParam) {
        return XxlJobRemotingUtil.postBody(addressUrl + "log", accessToken, timeout, logParam, LogResult.class);
    }

}
